package com.shop.zkmall.app.controller.a.live;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.shop.zkmall.app.domain.CereBuyerLiveRoom;
import com.shop.zkmall.app.mapper.CereBuyerLiveRoomMapper;

import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class LiveServiceImpl implements LiveService {

    @Resource
    private CereBuyerLiveRoomMapper liveRoomMapper;

    /**
     * 推流域名
     */
    private static final String PUSH_DOMAIN = "push.talktheprice.com";
    /**
     * 播放域名
     */
    private static final String PLAY_DOMAIN = "live.talktheprice.com";

    /**
     * 腾讯云密钥防盗链
     */
    private static final String TX_SECRET = "3cac10218f735ef02085416c61fa5451";

    @Override
    public CereBuyerLiveRoom createRoom(CereBuyerLiveRoom room) {
        if (room.getId() == null) {
            room.setId(IdWorker.getId());
        }
        room.setStatus(3); // 默认暂停中
        room.setCreateTime(LocalDateTime.now());
        room.setUpdateTime(LocalDateTime.now());
        liveRoomMapper.insert(room);
        return room;
    }

    @Override
    public CereBuyerLiveRoom getRoom(Long id) {
        return liveRoomMapper.selectById(id);
    }

    @Override
    public String generatePushUrl(Long roomId, long validSeconds) {
        CereBuyerLiveRoom room = liveRoomMapper.selectById(roomId);
        if (room == null) {
            throw new RuntimeException("直播间不存在");
        }

        String streamName = "room_" + roomId;  // 推流名称
        return LiveUrlUtil.buildPushUrl(PUSH_DOMAIN, streamName, TX_SECRET, validSeconds);
    }

    @Override
    public String generatePlayUrl(Long roomId) {
        String streamName = "room_" + roomId;
        return "https://" + PLAY_DOMAIN + "/live/" + streamName + ".flv";
    }

    @Override
    public void onStreamOnline(String streamName) {
        Long roomId = Long.parseLong(streamName.replace("room_", ""));
        CereBuyerLiveRoom room = liveRoomMapper.selectById(roomId);
        room.setStatus(1);
        room.setStartTime(LocalDateTime.now());
        room.setUpdateTime(LocalDateTime.now());
        liveRoomMapper.updateById(room);
    }

    @Override
    public void onStreamOffline(String streamName) {
        Long roomId = Long.parseLong(streamName.replace("room_", ""));
        CereBuyerLiveRoom room = liveRoomMapper.selectById(roomId);
        room.setStatus(2);
        room.setEndTime(LocalDateTime.now());
        room.setUpdateTime(LocalDateTime.now());
        liveRoomMapper.updateById(room);
    }
}
